const request = require('request');
const config = require('../config/config');

class js_plugin {

    constructor() {
    }

    async validCookie(cookie) {
        return new Promise((resolve, reject) => {
            let options = {
                url: 'https://ext.junglescout.com/api/v1/track_extension_event',
                method: 'POST',
                json: true,
                proxy: `http://${config.PROXY.HOST}:${config.PROXY.PORT}`,
                headers: {
                    "Authorization": `Bearer ${cookie}`,
                    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
                },
                body: `{"type":"track","event":"Extension - Fetch Data Using Embed","properties":{}}`
            };

            request(options, async (err, response, body) => {
                if (err) {
                    console.log(`js plugin cookie invalid. error:${JSON.stringify(err)}`);
                    if (err.code === 'ECONNRESET') {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                } else {
                    if (!body || body.error) {
                        console.log(`js plugin cookie invalid 1. Response:${JSON.stringify(body)}`);
                        resolve(false);
                    } else {
                        if (body.status) {
                            console.log(`js plugin cookie invalid pass... Status:${JSON.stringify(body)}`);
                            resolve(true);
                        } else {
                            console.log(`js plugin cookie invalid 2. Response:${JSON.stringify(body)}`);
                            resolve(false)
                        }
                    }
                }
            })
        })
    }
}

module.exports = js_plugin;
